package facade;

import remoteEntity.Fileblob;
import remoteEntity.Filedescription;
import remoteEntity.User;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

/**
 * FileblobFacade
 *
 * Handles the Filedescription database entities. Has functionality for
 * inserting into and deleting file descriptions from the database.
 */
@Stateless
public class FiledescriptionFacade extends AbstractFacade<Filedescription> {

    @PersistenceContext(unitName = "filecityeePU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public FiledescriptionFacade() {
        super(Filedescription.class);
    }

    public List<Filedescription> findByCategoryId(int catId, int[] range) {
        try {
            return em.createNamedQuery("Filedescription.findByCategoryId").
                    setParameter("categoryId", catId).setFirstResult(range[0]).
                    setMaxResults(range[1]).getResultList();
        } catch (NoResultException e) {
            return null;
        }
    }
    
    // LINDA
    public List<Filedescription> findAllFileDescriptions(){
        return em.createNamedQuery("Filedescription.findAll").getResultList();
    }

    public Filedescription findById(int id) {
        try {
            return (Filedescription) em.createNamedQuery("Filedescription.findById").setParameter("id", id).getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }

    public int countCategoryId(int catId) {
        try {
            return ((Long) em.createNamedQuery("Filedescription.countByCategoryId").
                    setParameter("categoryId", catId).getSingleResult()).intValue();
        } catch (NoResultException e) {
            return 0;
        }
    }

    public int insertFileDescriptor(String name, String description, User user, int category, Fileblob fb) {
        Filedescription fd = new Filedescription();
        fd.setName(name);
        fd.setDescription(description);
        fd.setUser(user);
        fd.setDatecreated(new Date());
        fd.setCategoryId(category);
        fd.setFileblob(fb);

        em.persist(fd);
        em.flush();
        return fd.getId();
    }

    public void delete(int id) {
        Filedescription fd = em.find(Filedescription.class, id);
        em.remove(fd);
        em.flush();
    }
}
